package com.example.springboot.controller.bookstore;

import com.example.springboot.bean.ProductRecord;
import com.example.springboot.bean.UserAccount;
import com.example.springboot.dao.ProductRecordDao;
import com.example.springboot.dao.UserAccountDao;
import com.example.springboot.service.CashierDeskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tang on 2018/3/8.
 */
@RestController
@RequestMapping("/userAccount")
public class UserAccountController {

    @Autowired
    private UserAccountDao userAccountDao;

    @Autowired
    private ProductRecordDao productRecordDao;

    @Autowired
    private CashierDeskService cashierDeskService;

    @RequestMapping("/findByName/{name}")
    public UserAccount findByName(@PathVariable(name = "name") String name) {
        UserAccount userAccount = userAccountDao.findByName(name);
        return userAccount;
    }

    @RequestMapping("/customerForm")
    public ModelAndView toCustomerFormPage(HttpServletRequest request) {

        ModelAndView mv = new ModelAndView();
        double totalPrice = 0;

        String[] checkBookIds = request.getParameterValues("checkBookId");
        List<ProductRecord> shoppingCart = new ArrayList<ProductRecord>();

        for (String id : checkBookIds) {
            ProductRecord productRecord = productRecordDao.findById(id);
            totalPrice = totalPrice + productRecord.getBookPrice();
            shoppingCart.add(productRecord);
        }

        mv.setViewName("bookstore/customer_form");
        request.getSession().setAttribute("shoppingCart", shoppingCart);
        mv.addObject("totalPrice", totalPrice);
        mv.addObject("shoppingCart", shoppingCart);

        return mv;

    }


    @RequestMapping("/confirmPurchase")
    public ModelAndView confirmPurchase(HttpServletRequest request) {

        ModelAndView mv = new ModelAndView();
        List<ProductRecord> purchaseBooks = (List<ProductRecord>) request.getSession().getAttribute("shoppingCart");
        String customerName = request.getParameter("customerName");

        cashierDeskService.checkOut(purchaseBooks, customerName);

        mv.setViewName("bookstore/purchase_success");
        return mv;
    }


}
